﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Windows.Forms;
using Braincase.GanttChart;
using Data.Models;
using Data.Models.Enums;
using Project_Schedule.Models;
using Adress = Project_Schedule.Models.Adress;
using Employee = Project_Schedule.Models.Employee;
using Operation = Project_Schedule.Models.Operation;
using Project = Data.Models.Project;
using Resource = Project_Schedule.Models.Resource;

namespace Project_Schedule
{
    public partial class MainForm : Form
    {
        private bool newAdressItem;
        private bool newEmployeeItem;
        private bool newItem;
        private bool newOperationItem;

        public MainForm()
        {
            InitializeComponent();
            foreach (object b in Enum.GetValues(typeof(ResourceType)))
            {
                typeDropDownList.Items.Add(b.ToString());
            }

            foreach (object b in Enum.GetValues(typeof(AdressType)))
            {
                adressTypeDropDownList.Items.Add(b.ToString());
            }

            using (var db = new ProjectScheduleContext())
            {
                IQueryable<ResourcesDto> query = db.Resources.Select(x => new ResourcesDto {Id = x.Id, Name = x.Name});
                employeeResourceDropDownList.DataSource = query.ToList();

                IQueryable<AdressDto> query1 = db.Employees.Select(x => new AdressDto {Id = x.Id, Name = x.Name, Surname = x.Surname});
                adressEmployeeDropDownList.DataSource = query1.ToList();

                IQueryable<OperationDto> query2 = db.Resources.Select(x => new OperationDto {Id = x.Id, Name = x.Name});
                operationResourceDropDownList.DataSource = query2.ToList();

                IQueryable<ProjectDto> query3 = db.Projects.Select(x => new ProjectDto {Id = x.Id, Name = x.Name});
                operationProjectDropDownList.DataSource = query3.ToList();

                IQueryable<ProjectDto> query4 = db.Projects.Select(x => new ProjectDto {Id = x.Id, Name = x.Name});
                projectDropDownList.DataSource = query4.ToList();
            }

            resourceGridView.SelectionChanged += resourceGridView_SelectionChanged;
            bZasobyNowy.Click += bZasobyNowy_Click;
            bZasobyOdśwież.Click += bZasobyOdśwież_Click;
            bZasobyZapisz.Click += bZasobyZapisz_Click;
            employeeGridView.SelectionChanged += employeeGridView_SelectionChanged;
            pagePracownicy.Enter += bPracownicyOdśwież_Click;
            pageDaneOs.Enter += bDaneOsOdśwież_Click;
            pageZadania.Enter += bZadaniaOdśwież_Click;
            pageZasoby.Enter += bZasobyOdśwież_Click;


        }


        private void bZasobyOdśwież_Click(object sender, EventArgs e)
        {
            using (var db = new ProjectScheduleContext())
            {
                IQueryable<Resource> query = db.Resources.OrderBy(b => b.Id).Select(b => new Resource
                                                                                             {
                                                                                                 Id = b.Id,
                                                                                                 Identyfikator = b.ResourceIdentifier,
                                                                                                 Nazwa = b.Name,
                                                                                                 Typ = b.ResourceType,
                                                                                                 Opis = b.Description
                                                                                             });

                resourceGridView.DataSource = query.ToArray();
            }
        }

        private void bZasobyNowy_Click(object sender, EventArgs e)
        {
            var isOk = !string.IsNullOrWhiteSpace(identTextBox.Text) &&
                       !string.IsNullOrWhiteSpace(nameTextBox.Text) &&
                       !string.IsNullOrWhiteSpace(typeDropDownList.Text);
            if (isOk)
            {
                newItem = true;
                bZasobyZapisz_Click(sender, e);
                newItem = false;

                identTextBox.Text = null;
                nameTextBox.Text = null;
                typeDropDownList.Text = null;
                descTextBox.Text = null;
            }
        }

        private void employeeGridView_SelectionChanged(object sender, EventArgs e)
        {
            newEmployeeItem = false;
            var employee = ((Employee)employeeGridView.CurrentRow.DataBoundItem);
            employeeNameTextBox.Text = employee.Imię;
            surnameTextBox.Text = employee.Nazwisko;
            employeeResourceDropDownList.SelectedIndex = employee.Zasób.HasValue
                                                             ? employeeResourceDropDownList.Items.First(
                                                                 x => x.Text.StartsWith(employee.Zasób.Value.ToString())).RowIndex
                                                             : -1;
            positionTextBox.Text = employee.Pozycja;

            employeeResourceDropDownList.Refresh();
        }

        private void resourceGridView_SelectionChanged(object sender, EventArgs e)
        {
            newItem = false;

            identTextBox.Text = ((Resource)resourceGridView.CurrentRow.DataBoundItem).Identyfikator.ToString();
            nameTextBox.Text = ((Resource)resourceGridView.CurrentRow.DataBoundItem).Nazwa;
            typeDropDownList.SelectedIndex = (int)((Resource)resourceGridView.CurrentRow.DataBoundItem).Typ;
            descTextBox.Text = ((Resource)resourceGridView.CurrentRow.DataBoundItem).Opis;
            typeDropDownList.Refresh();
        }

        private void bZasobyZapisz_Click(object sender, EventArgs e)
        {
            if (resourceGridView.CurrentRow == null)
                newItem = true;
            using (var db = new ProjectScheduleContext())
            {
                var new_resource = new Data.Models.Resource();

                if (!newItem)
                    new_resource.Id = ((Resource)resourceGridView.CurrentRow.DataBoundItem).Id;
                new_resource.ResourceIdentifier = int.Parse(identTextBox.Text);
                new_resource.Name = nameTextBox.Text;
                new_resource.ResourceType = (ResourceType)typeDropDownList.SelectedIndex;
                new_resource.Description = descTextBox.Text;

                if (!newItem)
                {
                    db.Resources.Attach(new_resource);
                    db.Entry(new_resource).State = EntityState.Modified;
                }
                else
                    db.Resources.Add(new_resource);

                db.SaveChanges();
            }
            bZasobyOdśwież_Click(sender, e);
        }

        private void bPracownicyOdśwież_Click(object sender, EventArgs e)
        {
            using (var db = new ProjectScheduleContext())
            {
                var query = db.Employees.Select(b => new {b, res = b.Resource}).OrderBy(@t => @t.b.Id).Select(@t => new Employee
                                                                                                                        {
                                                                                                                            Id = @t.b.Id,
                                                                                                                            Imię = @t.b.Name,
                                                                                                                            Nazwisko = @t.b.Surname,
                                                                                                                            Pozycja = @t.b.Position,
                                                                                                                            Zasób = @t.res.Id,
                                                                                                                            NazwaZasobu = @t.res.Name
                                                                                                                        });
                employeeGridView.DataSource = query.ToArray();
            }
        }

        private void bPracoznicyZapisz_Click(object sender, EventArgs e)
        {
            using (var db = new ProjectScheduleContext())
            {
                var new_employee = new Data.Models.Employee();

                if (!newEmployeeItem)
                    new_employee.Id = ((Employee)employeeGridView.CurrentRow.DataBoundItem).Id;
                new_employee.Name = employeeNameTextBox.Text;
                new_employee.Surname = surnameTextBox.Text;

                int? resId = null;
                if (employeeResourceDropDownList.SelectedIndex > -1)
                    resId = int.Parse(employeeResourceDropDownList.SelectedItem.Text.Split().First());


                new_employee.Position = positionTextBox.Text;

                if (resId != null)
                    new_employee.Resource = db.Resources.First(x => x.Id == (int)resId);

                if (!newEmployeeItem)
                {
                    if (resId == null)
                    {
                        db.Database.ExecuteSqlCommand(
                            "changeEmployeeResource @id",
                            new SqlParameter("id", new_employee.Id));
                    }
                    else
                    {
                        db.Database.ExecuteSqlCommand(
                            "changeEmployeeResource @id, @new",
                            new SqlParameter("id", new_employee.Id),
                            new SqlParameter("new", resId));
                    }
                    db.Employees.Attach(new_employee);
                    db.Entry(new_employee).State = EntityState.Modified;
                }
                else
                    db.Employees.Add(new_employee);

                db.SaveChanges();
            }
            bPracownicyOdśwież_Click(sender, e);
        }

        private void bPracownicyNowy_Click(object sender, EventArgs e)
        {
            var ok = !string.IsNullOrWhiteSpace(employeeNameTextBox.Text) &&
                     !string.IsNullOrWhiteSpace(surnameTextBox.Text) &&
                     !string.IsNullOrWhiteSpace(employeeResourceDropDownList.Text) &&
                     !string.IsNullOrWhiteSpace(positionTextBox.Text);
            if (ok)
            {
                newEmployeeItem = true;
                bPracoznicyZapisz_Click(sender, e);
                newEmployeeItem = false;

                employeeNameTextBox.Text = null;
                surnameTextBox.Text = null;
                employeeResourceDropDownList.Text = null;
                positionTextBox.Text = null;
            }

        }

        private void bDaneOsOdśwież_Click(object sender, EventArgs e)
        {
            using (var db = new ProjectScheduleContext())
            {
                IQueryable<Adress> query = db.Adresses.OrderBy(b => b.Id).Select(b => new Adress
                                                                                          {
                                                                                              Id = b.Id,
                                                                                              Typ = b.AdressType,
                                                                                              IdPracownika = b.Employee.Id,
                                                                                              Ulica = b.Street,
                                                                                              Dom = b.BuildingNumber,
                                                                                              Mieszkanie = b.FaltNumber,
                                                                                              Miejscowość = b.Locality,
                                                                                              Kraj = b.Country
                                                                                          });
                adressGridView.DataSource = query.ToArray();

                IQueryable<AdressDto> query2 = db.Employees.Select(x => new AdressDto { Id = x.Id, Name = x.Name, Surname = x.Surname });
                adressEmployeeDropDownList.DataSource = query2.ToList();
            }
        }

        private void adressGridView_SelectionChanged(object sender, EventArgs e)
        {
            newAdressItem = false;

            var adress = ((Adress)adressGridView.CurrentRow.DataBoundItem);

            streetTextBox.Text = adress.Ulica;
            buildingTextBox.Text = adress.Dom;
            adressTypeDropDownList.SelectedIndex = (int)(adress).Typ;
            flatTextBox.Text = adress.Mieszkanie;
            localityTextBox.Text = adress.Miejscowość;
            countryTextBox.Text = adress.Kraj;

            adressEmployeeDropDownList.SelectedIndex = adress.IdPracownika.HasValue
                                                           ? adressEmployeeDropDownList.Items.First(
                                                               x => x.Text.StartsWith(adress.IdPracownika.Value.ToString())).RowIndex
                                                           : -1;

            typeDropDownList.Refresh();
        }

        private void bDaneOsNowy_Click(object sender, EventArgs e)
        {
            var ok =
                !string.IsNullOrWhiteSpace(streetTextBox.Text) &&
                !string.IsNullOrWhiteSpace(buildingTextBox.Text) &&
                !string.IsNullOrWhiteSpace(adressTypeDropDownList.Text) &&
                !string.IsNullOrWhiteSpace(localityTextBox.Text) &&
                !string.IsNullOrWhiteSpace(countryTextBox.Text) &&
                !string.IsNullOrWhiteSpace(adressEmployeeDropDownList.Text);
            if (ok)
            {
                newAdressItem = true;
                bDaneOsZapisz_Click(sender, e);
                newAdressItem = false;

                streetTextBox.Text = null;
                buildingTextBox.Text = null;
                adressTypeDropDownList.SelectedIndex = -1;
                flatTextBox.Text = null;
                localityTextBox.Text = null;
                countryTextBox.Text = null;
                adressEmployeeDropDownList.SelectedIndex = -1;

                adressEmployeeDropDownList.Refresh();
                adressTypeDropDownList.Refresh();
            }


        }

        private void bDaneOsZapisz_Click(object sender, EventArgs e)
        {
            using (var db = new ProjectScheduleContext())
            {
                var newAdress = new Data.Models.Adress();

                if (!newAdressItem)
                    newAdress.Id = ((Adress)adressGridView.CurrentRow.DataBoundItem).Id;
                newAdress.Street = streetTextBox.Text;
                newAdress.BuildingNumber = buildingTextBox.Text;
                newAdress.AdressType = (AdressType)adressTypeDropDownList.SelectedIndex;
                newAdress.FaltNumber = flatTextBox.Text;
                newAdress.Locality = localityTextBox.Text;
                newAdress.Country = countryTextBox.Text;

                int? emplId = null;
                if (adressEmployeeDropDownList.SelectedIndex > -1)
                    emplId = int.Parse(adressEmployeeDropDownList.SelectedItem.Text.Split().First());

                if (emplId.HasValue)
                    newAdress.Employee = db.Employees.First(x => x.Id == emplId.Value);

                if (!newAdressItem)
                {
                    if (!emplId.HasValue)
                    {
                        db.Database.ExecuteSqlCommand(
                            "changeAdressEmployee @id",
                            new SqlParameter("id", newAdress.Id));
                    }
                    else
                    {
                        db.Database.ExecuteSqlCommand(
                            "changeAdressEmployee @id, @new",
                            new SqlParameter("id", newAdress.Id),
                            new SqlParameter("new", emplId.Value));
                    }
                    db.Adresses.Attach(newAdress);
                    db.Entry(newAdress).State = EntityState.Modified;
                }
                else
                    db.Adresses.Add(newAdress);

                db.SaveChanges();
            }
            bDaneOsOdśwież_Click(sender, e);
        }


        private void bZadaniaOdśwież_Click(object sender, EventArgs e)
        {
            using (var db = new ProjectScheduleContext())
            {
                IQueryable<Operation> query = db.Operations.OrderBy(b => b.Id).Select(b => new Operation
                                                                                               {
                                                                                                   Id = b.Id,
                                                                                                   Identyfikator = b.Order,
                                                                                                   Nazwa = b.Name,
                                                                                                   Czas = b.Duration,
                                                                                                   Następniki = b.NextOperation,
                                                                                                   Opis = b.Description,
                                                                                                   Zasób = b.Resource.Id,
                                                                                                   NazwaZasobu = b.Resource.Name,
                                                                                                   Projekt = b.Project.Id
                                                                                               });
                operationGridView.DataSource = query.ToArray();
            }
        }

        private void operationGridView_SelectionChanged(object sender, EventArgs e)
        {
            newOperationItem = false;
            var operation = ((Operation)operationGridView.CurrentRow.DataBoundItem);


            orderTextBox.Text = operation.Identyfikator.ToString();
            operationNameTextBox.Text = operation.Nazwa;
            durationTextBox.Text = operation.Czas.ToString();
            nextOperationTextBox.Text = operation.Następniki;
            operationDescriptionTextBox.Text = operation.Opis;

            operationResourceDropDownList.SelectedIndex = operation.Zasób.HasValue
                                                              ? operationResourceDropDownList.Items.First(
                                                                  x => x.Text.StartsWith(operation.Zasób.Value.ToString())).RowIndex
                                                              : -1;
            operationProjectDropDownList.SelectedIndex = operation.Projekt.HasValue
                                                             ? operationProjectDropDownList.Items.First(
                                                                 x => x.Text.StartsWith(operation.Projekt.Value.ToString())).RowIndex
                                                             : -1;

            operationProjectDropDownList.Refresh();
            operationResourceDropDownList.Refresh();
        }

        private void bZadaniaNowy_Click(object sender, EventArgs e)
        {

            var ok =
                !string.IsNullOrWhiteSpace(operationNameTextBox.Text) &&
                !string.IsNullOrWhiteSpace(durationTextBox.Text);
              

            if (ok)
            {
                newOperationItem = true;
                bZadaniaZapisz_Click(sender, e);
                newOperationItem = false;

                operationResourceDropDownList.SelectedIndex = -1;
                operationProjectDropDownList.SelectedIndex = -1;

                orderTextBox.Text = null;
                operationNameTextBox.Text = null;
                durationTextBox.Text = null;
                nextOperationTextBox.Text = null;
                operationDescriptionTextBox.Text = null;

                operationResourceDropDownList.SelectedIndex = -1;
                operationProjectDropDownList.SelectedIndex = -1;
            }
            operationProjectDropDownList.Refresh();
            operationResourceDropDownList.Refresh();
        }

        private void bZadaniaZapisz_Click(object sender, EventArgs e)
        {
            using (var db = new ProjectScheduleContext())
            {
                var newOperation = new Data.Models.Operation();

                if (!newOperationItem)
                    newOperation.Id = ((Operation)operationGridView.CurrentRow.DataBoundItem).Id;
                newOperation.Order = string.IsNullOrWhiteSpace(orderTextBox.Text) ?null:(int?)int.Parse(orderTextBox.Text);
                newOperation.Name = operationNameTextBox.Text;
                newOperation.Duration = int.Parse(durationTextBox.Text);
                newOperation.NextOperation = nextOperationTextBox.Text;
                newOperation.Description = operationDescriptionTextBox.Text;

                int? reslId = null;
                if (operationResourceDropDownList.SelectedIndex > -1)
                    reslId = int.Parse(operationResourceDropDownList.SelectedItem.Text.Split().First());

                int? projId = null;
                if (operationProjectDropDownList.SelectedIndex > -1)
                    projId = int.Parse(operationProjectDropDownList.SelectedItem.Text.Split().First());

                if (reslId != null)
                    newOperation.Resource = db.Resources.First(x => x.Id == (int)reslId);

                if (reslId != null)
                    newOperation.Project = db.Projects.First(x => x.Id == (int)projId);


                if (!newOperationItem)
                {
                    if (reslId == null)
                    {
                        db.Database.ExecuteSqlCommand(
                            "changeOperationResource @id",
                            new SqlParameter("id", newOperation.Id));
                    }
                    else
                    {
                        db.Database.ExecuteSqlCommand(
                            "changeOperationResource @id, @new",
                            new SqlParameter("id", newOperation.Id),
                            new SqlParameter("new", reslId));
                    }

                    if (projId == null)
                    {
                        db.Database.ExecuteSqlCommand(
                            "changeOperationProject @id",
                            new SqlParameter("id", newOperation.Id));
                    }
                    else
                    {
                        db.Database.ExecuteSqlCommand(
                            "changeOperationProject @id, @new",
                            new SqlParameter("id", newOperation.Id),
                            new SqlParameter("new", projId));
                    }

                    db.Operations.Attach(newOperation);
                    db.Entry(newOperation).State = EntityState.Modified;
                }
                else
                    db.Operations.Add(newOperation);

                db.SaveChanges();
            }
            bZadaniaOdśwież_Click(sender, e);
        }


        private void bNewProj_Click(object sender, EventArgs e)
        {
            using (var db = new ProjectScheduleContext())
            {
                var new_project = new Project { Name = projectTextBox.Text, Description = projectDescriptionTextBox.Text };

                db.Projects.Add(new_project);
                db.SaveChanges();


                IQueryable<ProjectDto> query = db.Projects.Select(x => new ProjectDto { Id = x.Id, Name = x.Name });
                projectDropDownList.DataSource = query.ToList();


                projectDropDownList.Refresh();
            }
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(projectDropDownList.Text))
            {
                var formGant = new GanttForm(int.Parse(projectDropDownList.Text.Split().First()));
                formGant.Show();
            }
        }



    }
}